package com.empire.module.member.controller.admin.presentation;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.validation.annotation.Validated;

import com.empire.framework.apilog.core.annotation.ApiAccessLog;

import static com.empire.framework.apilog.core.enums.OperateTypeEnum.*;
import com.empire.framework.common.pojo.CommonResult;
import com.empire.framework.common.pojo.PageParam;
import com.empire.framework.common.pojo.PageResult;
import com.empire.framework.common.util.object.BeanUtils;
import static com.empire.framework.common.pojo.CommonResult.success;
import com.empire.framework.excel.core.util.ExcelUtils;

import com.empire.module.member.controller.admin.presentation.vo.*;
import com.empire.module.member.dal.dataobject.presentation.PresentationDO;
import com.empire.module.member.service.presentation.PresentationService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Tag(name = "管理后台 - 报告")
@RestController
@RequestMapping("/member/presentation")
@Validated
public class PresentationController {

    @Resource
    private PresentationService presentationService;

    @PostMapping("/create")
    @Operation(summary = "创建报告")
    @PreAuthorize("@ss.hasPermission('member:presentation:create')")
    @ApiAccessLog(operateType = CREATE)
    public CommonResult<Long> createPresentation(@Valid @RequestBody PresentationSaveReqVO createReqVO) {
        return success(presentationService.createPresentation(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新报告")
    @PreAuthorize("@ss.hasPermission('member:presentation:update')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> updatePresentation(@Valid @RequestBody PresentationSaveReqVO updateReqVO) {
        presentationService.updatePresentation(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除报告")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('member:presentation:delete')")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Boolean> deletePresentation(@RequestParam("id") Long id) {
        presentationService.deletePresentation(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得报告")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('member:presentation:query')")
    public CommonResult<PresentationRespVO> getPresentation(@RequestParam("id") Long id) {
        PresentationDO presentation = presentationService.getPresentation(id);
        return success(BeanUtils.toBean(presentation, PresentationRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得报告分页")
    @PreAuthorize("@ss.hasPermission('member:presentation:query')")
    public CommonResult<PageResult<PresentationRespVO>> getPresentationPage(@Valid PresentationPageReqVO pageReqVO) {
        PageResult<PresentationDO> pageResult = presentationService.getPresentationPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, PresentationRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得报告列表")
    @PreAuthorize("@ss.hasPermission('member:presentation:query')")
    public CommonResult<List<PresentationItemRespVO>> getPresentationList() {
        List<PresentationDO> list = presentationService.getPresentationList();
        return success(BeanUtils.toBean(list, PresentationItemRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出报告 Excel")
    @PreAuthorize("@ss.hasPermission('member:presentation:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportPresentationExcel(@Valid PresentationPageReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<PresentationDO> list = presentationService.getPresentationPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "报告.xls", "数据", PresentationRespVO.class,
                BeanUtils.toBean(list, PresentationRespVO.class));
    }

    /**
     * 下载报告文件
     */
    @GetMapping("/download/{id}")
    @Operation(summary = "下载报告文件")
    @Parameter(name = "id", description = "报告编号", required = true)
    @PreAuthorize("@ss.hasPermission('member:presentation:query')")
    public void downloadPresentation(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        presentationService.downloadFile(response, id);
    }

    /**
     * 上传HTML文件并转换为Word
     */
    @PostMapping("/merge-binary/{id}")
    @Operation(summary = "上传HTML并生成Word文件")
    @Parameter(name = "id", description = "报告编号", required = true)
    @PreAuthorize("@ss.hasPermission('member:presentation:update')")
    public CommonResult<Boolean> mergeBinaryData(
            @PathVariable("id") Long id,
            @RequestParam("file") MultipartFile file) throws IOException {

        // 创建临时文件
        File tempFile = File.createTempFile("presentation_", ".html");
        try {
            // 转移文件内容到临时文件
            file.transferTo(tempFile);
            // 调用服务处理
            boolean result = presentationService.mergeBinaryData(id, tempFile);
            return success(result);
        } finally {
            // 清理临时文件
            if (tempFile.exists() && !tempFile.delete()) {
                // 记录清理失败日志
                System.err.println("Failed to delete temporary file: " + tempFile.getAbsolutePath());
            }
        }
    }

}
